<template>
  <component :is="tag" v-if="hasPermission" v-bind="$attrs">
    <slot />
  </component>
</template>

<script setup lang="ts">
import { computed } from 'vue'
import type { Permission } from '@/types'

// 组件属性定义
interface Props {
  /** 权限标识 - 需要验证的权限key */
  permission: string
  /** 渲染的HTML标签，默认为span */
  tag?: string
}

const props = withDefaults(defineProps<Props>(), {
  tag: 'span',
})

// 获取缓存的权限数据
function getCachedPermissions(): Permission[] | null {
  try {
    const cached = localStorage.getItem('user_permissions_cache')
    if (!cached) return null

    const cacheItem = JSON.parse(cached)
    const now = Date.now()

    // 检查是否过期
    if (now - cacheItem.timestamp > cacheItem.expiry) {
      localStorage.removeItem('user_permissions_cache')
      return null
    }

    return cacheItem.data
  } catch (error) {
    localStorage.removeItem('user_permissions_cache')
    return null
  }
}

// 检查是否有指定权限
const hasPermission = computed(() => {
  if (!props.permission) {
    console.warn('PermissionButton: permission 属性是必需的')
    return false
  }

  const cachedPermissions = getCachedPermissions()
  if (!cachedPermissions || cachedPermissions.length === 0) {
    console.warn('PermissionButton: 未找到权限缓存数据')
    return false
  }

  // 查找对应的按钮权限 (type=2为操作按钮权限)
  const buttonPermission = cachedPermissions.find(
    (p) =>
      p.permissionKey === props.permission &&
      p.type === 2 &&
      (p.show === undefined || p.show === 1) &&
      p.permissionStatus === 'enabled'
  )

  return !!buttonPermission
})
</script>

<script lang="ts">
/**
 * PermissionButton 权限按钮组件
 *
 * @description
 * 根据用户权限控制按钮是否显示，支持任意HTML标签渲染
 *
 * @example
 * ```vue
 * <!-- 基础用法 -->
 * <PermissionButton permission="system:menu:add">
 *   <a-button type="primary">新增菜单</a-button>
 * </PermissionButton>
 *
 * <!-- 指定渲染标签 -->
 * <PermissionButton permission="system:menu:edit" tag="div">
 *   <a-button type="link">编辑</a-button>
 * </PermissionButton>
 *
 * <!-- 多个按钮组合 -->
 * <a-space>
 *   <PermissionButton permission="system:menu:add">
 *     <a-button type="primary">新增</a-button>
 *   </PermissionButton>
 *   <PermissionButton permission="system:menu:edit">
 *     <a-button type="default">编辑</a-button>
 *   </PermissionButton>
 *   <PermissionButton permission="system:menu:delete">
 *     <a-button type="primary" danger>删除</a-button>
 *   </PermissionButton>
 * </a-space>
 * ```
 *
 * @props
 * - permission: string - 权限标识，对应权限表中的permissionKey字段
 * - tag: string - 渲染的HTML标签，默认为span
 *
 * @notes
 * - 组件会自动从localStorage读取权限缓存
 * - 只有type=2且status=enabled的权限会被认为是有效的按钮权限
 * - 如果权限缓存过期或不存在，按钮将不显示
 * - 支持v-bind透传所有属性到渲染的标签
 *
 * @author Jqchan
 * @since 2025-05-31
 */
export default {
  name: 'PermissionButton',
}
</script> 